$(document).ready(function () {


    layui.config({
        base: '../static/js/modules/' //假设这是你存放拓展模块的根目录
    }).extend({ //设定模块别名
        tag: 'tag' //如果 tag.js 是在根目录，也可以不用设定别名
    }).use('tag', function () {

        var layer = layui.layer;

        laydate = layui.laydate;

        table = layui.table;

        transfer = layui.transfer;

        element = layui.element;

        // 表格
        form = layui.form;
        form.on('select(needCharge)', function (data) {//监听是否充电查询条件下拉
            $('div[lay-filter="search"]').click();
        });

        form.on('radio(searchType)', function (data) {
            $('div[lay-filter="search"]').click();
        });

        form.on('submit(search)', function (data) {//监听查询提交
            params = data.field;
            params.pageSize = 10;
            queryTable()
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });


        form.on('submit(edit)', function (data) {//监听新增修改提交

            let msgType = "";
            if (curId) {
                msgType = "编辑"
                data.field.id = curId
            } else {
                msgType = "新增"
            }

            new AjaxChain()
                .setUrl('/device/save')
                .setMethod('post')
                .setData(JSON.stringify(data.field))
                .then(data => {
                    layer.close(drawer);
                    layer.msg(msgType + '成功', { icon: 1, time: 2000 });
                    queryTable()
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();


            return false;
        });


        initSubMenu();
        queryTable();
        queryType();

    });

})
var params = {};//查询条件参数
var form, unit, laydate, tag, table, transfer, element;//layui模块
var drawer;//抽屉实例
var curId = null;//当前选中设备ID
var curDeviceCode = null;//节点下行当前设备编号

// 查询设备类型
queryType = () => {

    $('.device-item').empty().append(new ST().device(1).reduce(
        (x, y) => {
            return x +
                `
            <input lay-filter="searchType" type="radio" name="type" value="${y.type}" lay-skin="none">
            <div lay-radio class="lay-skin-tag layui-badge">${y.name}</div>
            `

        }, `<input lay-filter="searchType" type="radio" name="type" value="" lay-skin="none" checked>
            <div lay-radio class="lay-skin-tag layui-badge">全部</div>`
    ))

    form.render();
}
// 查询表格数据
queryTable = () => {

    let toolWidth = window.innerWidth / 1920 * 360

    var dropdown = layui.dropdown;

    //展示已知数据
    table.render({
        elem: '#table'
        , text: {
            none: '暂无数据'
        }
        , method: 'get'
        , url: ajaxPrefix() + "/device/list"
        , headers: {
            SessionId: JSON.parse(localStorage.getItem('sessionId'))
        }
        , where: params
        , parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.status == 200 ? 0 : 1, //解析接口状态
                "msg": res.message, //解析提示文本
                "count": res.result.total, //解析数据长度
                "data": res.result.data //解析数据列表
            };
        }
        , request: {
            pageName: 'pageNum' //页码的参数名称，默认：page
            ,
            limitName: 'pageSize' //每页数据量的参数名，默认：limit
        }
        , cols: [[ //标题栏
            { field: 'name', title: '设备名称', align: "left", width: 250, }
            , { field: 'code', title: '设备编号', align: "left" }
            , { field: 'typeDesc', title: '设备类型', align: "center" }
            , { field: 'simId', title: 'sim卡号', align: "center" }
            // , { field: 'linkMan', title: '联系人', align: "center" }
            , {
                field: 'notifySms', title: '短信通知', align: "center"
                , templet: function (d) {
                    let res = JSON.stringify(d);
                    return d.notifySms == 1 ? `
                    <span onclick='noticeSave(${res})' 
                    class="layui-badge layui-bg-green">已配置</span>`
                        : `<span onclick='noticeSave(${res})' 
                        class="layui-badge layui-bg-gray">未配置</span>`
                },
            }
            , {
                field: 'notifyVms', title: '语音通知', align: "center"
                , templet: function (d) {
                    let res = JSON.stringify(d);
                    return d.notifyVms == 1 ? `
                    <span onclick='noticeSave(${res})' 
                    class="layui-badge layui-bg-green">已配置</span>`
                        : `<span onclick='noticeSave(${res})' 
                        class="layui-badge layui-bg-gray">未配置</span>`
                },
            }
            , {
                title: '操作',
                align: 'center',
                width: toolWidth,
                toolbar: '#table-tool',
            },
        ]]
        , height: 'full'
        // ,skin: 'line' //表格风格
        , even: true
        , page: {
            layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
            //,curr: 5 //设定初始在第 5 页
            , groups: 3 //只显示 1 个连续页码
            , first: false //不显示首页
            , last: false //不显示尾页

        }
        , done: function (res, curr, count) {

            $('.layui-table-cell').height($('.contain-table-list').height() / 20);
        },

    });

    // 行工具事件
    table.on('tool(table)', function (obj) {
        var that = this;
        var res = obj.data;

        if (obj.event === 'more') {
            let moreOP = [{
                title: '告警通知',
                id: '5'
            }]
            if (res.type == 4)//人脸识别设备
            {
                moreOP.push({
                    title: '人脸下行',
                    id: '6'
                })
            }
            if (res.type == 5)//手动报警设备
            {
                moreOP.push({
                    title: '设备关联',
                    id: '7'
                })
            }
            if (res.type == 7)//远程断电设备
            {
                moreOP.push({
                    title: '节点配置',
                    id: '8'
                })
            }
            if (res.type == 1)//rfid设备
            {
                moreOP.push({
                    title: 'rfid操作',
                    id: '9'
                })
                moreOP.push({
                    title: 'rfid配置',
                    id: '10'
                })
            }


            // 更多下拉菜单
            dropdown.render({
                elem: that,
                show: true, // 外部事件触发即显示
                data: moreOP,
                click: function (data, othis) {
                    //根据 id 做出不同操作
                    if (data.id === '5') {//告警通知配置

                        noticeSave(res)

                    } else if (data.id === '6') {//人脸下行
                        openPersonPhoto(res.id)
                    }
                    else if (data.id === '7') {//设备关联
                        openBound(res.id)
                    }
                    else if (data.id === '8') {//节点配置
                        curDeviceCode = res.code
                        queryNodeList(res.id)
                    }
                    else if (data.id === '9') {//rfid操作

                        layer.alert('请选择您的操作', {

                            btn: ['打开', '关闭', '重启'],

                            btnAlign: 'c', // 按钮居中显示

                            btn1: function () {


                                rfidAction(res.id, 1)

                            },

                            btn2: function () {

                                rfidAction(res.id, 2)

                            },

                            btn3: function () {

                                rfidAction(res.id, 3)

                            }

                        });

                    }
                    else if (data.id === '10') {//rfid配置
                        rfidConfig(res.id)
                    }


                },
                align: 'right', // 右对齐弹出
                style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
            })
        } else {
            tableHandle(parseInt(obj.event), res)
        }
    });

}


// 列表功能按钮操作
tableHandle = (type, res) => {
    switch (type) {
        case 1://编辑
            curId = res.id
            openDrawer(2, res)
            break;
        case 2://删除

            layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/device/delete')
                    .setData({ id: res.id })
                    .then(data => {
                        layer.msg('删除成功', { icon: 1, time: 1500 });
                        queryTable();
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });
            break;

        case 3://新增 
            curId = null;
            openDrawer(1)
            break;
        case 4://设备报文
            openReport(res.id)
            break;

        default:
            break;
    }
}


// 编辑新增弹窗
openDrawer = (type, res) => {
    drawer = layer.open({
        title: (type == 1 ? "新增" : "编辑") + '设备',
        type: 1,
        offset: 'r',
        anim: 'slideLeft', // 从右往左
        area: ['30%', '100%'],
        shade: 0.3,
        shadeClose: false,
        id: 'edit-offset',
        success: function (layero, index, that) {
            laydate.render({
                elem: '#expiryDate',
                trigger: 'click',
            });

            if (res) {
                form.val('editForm', res);

            } else {
                form.render(null, 'editForm');
            }
        },
        content: `<form class="layui-form layui-form-pane" id="add-form"  lay-filter="editForm"  action="">
                    <div class="form-item">
                        <label class="layui-form-label">设备名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" lay-affix="clear" placeholder="请输入" lay-verify="required"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">设备编号</label>
                        <div class="layui-input-block">
                            <input type="text" name="code" lay-affix="clear" placeholder="请输入" lay-verify="required"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">设备类型</label>
                        <div class="layui-input-block">
                            <select name="type" lay-filter="" lay-verify="required">
                                ${new ST().device()}
                            </select>
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">sim卡号</label>
                        <div class="layui-input-block">
                            <input type="text" name="simId" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">联系人</label>
                        <div class="layui-input-block">
                            <input type="text" name="linkMan" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">联系方式</label>
                        <div class="layui-input-block">
                            <input type="text" name="linkPhone" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item pane-tool" >
                        <button type="reset" class="layui-btn layui-btn-primary btn-reset">重置</button>
                        <button class="layui-btn" lay-submit lay-filter="edit">确认</button>
                    </div>
                </form>`
    });

}


//设备历史报文列表
openReport = (id) => {
    layer.open({
        title: '历史报文',
        maxmin: true,
        type: 1,
        offset: 'r',
        anim: 'slideLeft', // 从右往左
        area: ['45%', '100%'],
        shade: 0.3,
        shadeClose: false,
        id: 'report-offset',
        full: function () {

            table.resize('record-table');

        },

        restore: function () {

            table.resize('record-table');

        },
        success: function (layero, index, that) {

            table.render({
                elem: '#record-table'
                , text: {
                    none: '暂无数据'
                }
                , method: 'get'
                , url: ajaxPrefix() + "/device/report/list"
                , headers: {
                    SessionId: JSON.parse(localStorage.getItem('sessionId'))
                }
                , where: {
                    deviceId: id,
                }
                , parseData: function (res) { //res 即为原始返回的数据
                    return {
                        "code": res.status == 200 ? 0 : 1, //解析接口状态
                        "msg": res.message, //解析提示文本
                        "count": res.result.total, //解析数据长度
                        "data": res.result.data
                    };
                }
                , request: {
                    pageName: 'pageNum' //页码的参数名称，默认：page
                    ,
                    limitName: 'pageSize' //每页数据量的参数名，默认：limit
                }
                , cols: [[ //标题栏
                    { field: 'dataTime', title: '上报时间', align: "center", width: 250, sort: true, }
                    , { field: 'content', title: '原始报文', alignL: 'left' }
                ]]
                , height: 'full-50'
                // ,skin: 'line' //表格风格
                , even: true
                , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                    groups: 3 //只显示 1 个连续页码
                    , first: false //不显示首页
                    , last: false //不显示尾页
                }
            });

            table.on('row(record-table)', function (obj) {

                var data = obj.data; // 得到当前行数据
                // 创建临时输入框
                const $temp = $("<textarea>");
                $("body").append($temp);
                // 获取要复制的文本
                const textToCopy = data.content;
                // 写入并选中文本
                $temp.val(textToCopy).select();
                // 执行复制命令
                document.execCommand("copy");
                // 移除临时元素
                $temp.remove();
                layer.msg('已将报文复制到剪切板', { offset: ['0px', '75%'] })

            });

        },
        content: ` <table id="record-table" lay-filter="record-table"></table>`
    });

}

//配置设备通知
noticeSave = (res) => {

    let str = ''

    if (res.linkPhone != null && res.linkPhone != '') {

        str = res.linkPhone.split(',').reduce((x, y) => {
            return x + ` <button lay-id="" type="button" class="tag-item">${y}</button>`
        }, '')
    }

    layer.open({
        type: 1,
        area: '40%',
        resize: false,
        shadeClose: true,
        title: '通知配置',
        content: `<form class="layui-form layui-form-pane" id="notice-form" lay-filter="noticeForm" action="">
                    <div class="form-item">
                        <label class="layui-form-label">通知方式</label>
                        <div class="layui-input-block checkbox-input">
                            <input type="checkbox" name="notifySms" title="短信">
                            <input type="checkbox" name="notifyVms" title="语音">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">联系人</label>
                        <div class="layui-input-block">
                            <input type="text" name="linkMan" lay-affix="clear" placeholder="请输入"  class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">联系方式</label>
                        <div class="layui-input-block tag"  lay-filter="linkPhone" lay-allowclose="true" lay-newTag="true">
                        ${str}
                        </div>
                    </div>
                    <div class="form-item pane-tool">
                        <div class="layui-btn layui-edit-submit" lay-submit  lay-filter="notice-edit">确认</div>
                    </div>
                </form>`,
        success: function (layero, index, that) {
            tag = layui.tag; //Tag的切换功能，切换事件监听等，需要依赖tag模块
            tag.render();

            tag.on('delete(linkPhone)', function (data) {
                $('.button-new-tag').show()
            });

            form.render();

            form.val('noticeForm', res);

            form.on('submit(notice-edit)', function (data) {
                var field = data.field;
                field.id = res.id;

                var linkPhoneArr = []

                $('.tag>.tag-item').each(function (i) {
                    linkPhoneArr.push($(this).text().slice(0, -1))
                });

                // if (!field.notifySms && !field.notifyVms) {
                //     layer.msg('请至少选择一种通知类型', { time: 1000, icon: 2 })
                //     return
                // }

                var linkPhone = linkPhoneArr.join(',')
                if (linkPhone == '') {
                    layer.msg('请填写通知号码', { time: 1000, icon: 2 })

                } else {

                    !field.notifySms ? field.notifySms = 0 : field.notifySms = 1
                    !field.notifyVms ? field.notifyVms = 0 : field.notifyVms = 1
                    field.linkPhone = linkPhone;

                    new AjaxChain()
                        .setUrl('/device/notice/save')
                        .setMethod('post')
                        .setData(JSON.stringify(field))
                        .then(data => {
                            layer.close(index);
                            layer.msg('配置成功', { icon: 1, time: 2000 });
                            queryTable()
                        })
                        .catch(err => {
                            console.error('请求异常:', err);
                        })
                        .send();
                }

                return false;
            });
        },
    });
}


// 设备绑定弹窗
openBound = (id) => {
    layer.open({
        type: 1,
        title: "设备关联",
        move: false,
        content: '<div id="bound-transfer"></div>',
        area: ['100%', '100%'], // 初始宽高
        success: function (layero, index) {

            new AjaxChain()
                .setUrl('/device/link/info')
                .setMethod('get')
                .setData(
                    {
                        deviceId: id,
                        types: 3,
                    }
                )
                .then(data => {

                    var boundValue = $.map(data.bound, function (obj) {
                        return obj.type + "*" + obj.deviceId;
                    });

                    let resdata = data.bound.concat(data.unbound)
                    // 渲染

                    transfer.render({
                        elem: '#bound-transfer',
                        id: 'boundTransfer',
                        data: resdata,
                        width: $('#bound-transfer').parent().width() / 2 - 100,
                        height: $('#bound-transfer').parent().height() - 100,
                        title: ['可绑定设备', '已绑定设备'],
                        showSearch: true,
                        value: boundValue,
                        onchange: function (data, index) {
                            let bound = $.map(transfer.getData('boundTransfer'), function (obj) {
                                return {
                                    "deviceId": obj.value.split('*')[1],
                                    "type": obj.value.split('*')[0],
                                };
                            });

                            new AjaxChain()
                                .setUrl('/device/link/save')
                                .setMethod('post')
                                .setData(JSON.stringify({
                                    "deviceId": id,
                                    "type": 5,
                                    "link": bound
                                }))
                                .then(data => {
                                    layer.msg('配置成功', { icon: 1, time: 800 });
                                })
                                .catch(err => {
                                    console.error('请求异常:', err);
                                })
                                .send();
                        },
                        parseData: function (res) {
                            return {
                                "value": res.type + "*" + res.deviceId, // 数据值
                                "title": "设备编号：" + res.deviceCode + '&nbsp;'.repeat(50 - res.deviceCode.length) + res.deviceName, // 数据标题
                            }

                        },

                    });

                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();

        }

    });

}


// 人脸下行弹窗
openPersonPhoto = (id) => {
    curId = id;
    layer.open({
        type: 1,
        title: "人脸识别照片录入",
        move: false,
        content: $('#photo-tool').html(),
        area: ['100%', '100%'], // 初始宽高
        success: function (layero, index) {

            let iH = $('.photo-already-list').parent().parent().height() - $('.layui-layer-title').height()

            $('.photo-con').css('height', iH)

            new AjaxChain()
                .setUrl('/person/list')
                .setMethod('get')
                .setData({
                    "pageNum": 1,
                    "pageSize": 10000
                })
                .then(data => {

                    $('.photo-all-list').empty().append(data.data.reduce((x, y) => {

                        if (y.photoPath == "" || y.photoPath == null) {
                            var img = '../static/img/nophoto.png'
                            var cl = 'import-no-choose'
                        } else {
                            var img = "/images/" + y.photoPath
                            var cl = ''
                        }

                        return x + `<div class="layui-col-md3">
                                <div class="photo-card" data-id="${y.id}" onclick=choosePhoto(this)>
                                    <img class="${cl}" src="${img}">
                                    <div class="photo-msg" style="justify-content: flex-start;color:#ddd;">
                                    <i class="layui-edge layui-edge-right" style="border-left-color: #46eef7;"></i>
                                    <i class="layui-edge layui-edge-right" style="border-left-color: #43bbea;"></i>
                                    ${y.name}
                                    </div>
                                </div>
                            </div>
                    `
                    }, ''))

                    queryPhotoByDevice()

                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();



        }
    });

}

// 选中照片事件
function choosePhoto(t) {

    if (!($(t).find('img').attr('class') == 'import-no-choose')) {

        $(t).toggleClass('photo-choose');

        $('.photo-choose').length == 0 ? ($('.import').addClass('import-no-choose')) : ($('.import').removeClass('import-no-choose'))

    } else {

        layer.confirm('该人员未上传照片，是否跳转上传?', { icon: 3 }, function (index) {

            window.open("firemen.html");

            layer.close(index); // 关闭弹层

        });


    }


}


// 导出人脸照片按钮
function savePhoto() {

    if ($('.photo-choose').length == 0) return

    var personIds = [];
    $('.photo-choose').each(function () {

        personIds.push($(this).data().id);

    });

    new AjaxChain()
        .setUrl('/person/photo/down')
        .setMethod('post')
        .setData(JSON.stringify({
            "personIds": personIds,
            "deviceIds": [curId],
        }))
        .enableLayer('录入成功',
            function () {
                $('.photo-card').removeClass('photo-choose')
                $('.import').addClass('import-no-choose')
            })
        .then(data => {
            queryPhotoByDevice()

        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();

}


//查询设备已录入照片

function queryPhotoByDevice() {

    new AjaxChain()
        .setUrl('/person/device/photo/list')
        .setMethod('get')
        .setData({
            "deviceId": curId,
        })
        .then(data => {

            var str = '';
            if (data.length == 0) {

                str = `<div class="layui-col-md6">
                        <div class="photo-card" style="display: flex;align-items: center;justify-content: center;">暂未录入人脸信息</div>
                    </div>`

            } else {
                str = data.reduce((x, y) => {

                    return x + `<div class="layui-col-md6" id="photo-${y.personId}">
                        <div class="photo-card">
                            <img src="/images/${y.photoPath}" >
                            <div class="photo-msg">
                                <span class="layui-badge layui-bg-blue">${y.personName}</span>
                                <span class="layui-badge layui-bg-gray">${$.calculateAge(y.birthDate) || "-"}</span>
                                <span class="layui-badge layui-bg-green photo-del" onclick=refreshPhoto("${y.personId}","${y.deviceId}")><i class="layui-icon layui-icon-refresh-3"
                                        style="font-size: 0.14rem;"></i>同步</span>
                                <span class="layui-badge photo-del" onclick=deletePhoto("${y.personId}","${y.deviceId}")><i class="layui-icon layui-icon-delete"
                                        style="font-size: 0.14rem;"></i>删除</span>

                            </div>
                        </div>
                    </div>
    `
                }, '')
            }

            $('.photo-already-list1').empty().append(str)


        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();
}


// 删除人脸照片
function deletePhoto(personId, deviceId) {
    layer.confirm('是否将照片从该设备中移除?', { icon: 3 }, function () {

        new AjaxChain()
            .setUrl('/person/photo/delete')
            .setMethod('post')
            .setData(JSON.stringify({
                "personIds": [personId],
                "deviceIds": [deviceId],
            }))
            .enableLayer('移除成功',
                function () {
                }, 20)
            .then(data => {

                $('#photo-' + personId).remove()

            })
            .catch(err => {
                console.error('请求异常:', err);
            })
            .send();

    });

}
// 刷新人脸照片
function refreshPhoto(personId, deviceId) {

    new AjaxChain()
        .setUrl('/person/photo/down')
        .setMethod('post')
        .setData(JSON.stringify({
            "personIds": [personId],
            "deviceIds": [deviceId],
        }))
        .enableLayer('同步成功',
            function () {
            }, 20)
        .then(data => {

            queryPhotoByDevice()

        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();

}

// 远程断电节点弹窗列表
queryNodeList = (id) => {

    layer.open({
        title: `<div style="height: 100%;display: flex;align-items: center;">
                    <div class="table-edit layui-btn" onclick=addNewNodes("${id}",1)> 
                        <img src="../static/img/report.png">新增节点
                    </div>
                </div>`,
        maxmin: true,
        type: 1,
        offset: 'r',
        anim: 'slideLeft', // 从右往左
        area: ['45%', '100%'],
        shade: 0.3,
        shadeClose: false,
        move: false,
        id: 'rd-offset',
        full: function () {

            table.resize('node-table');

        },
        restore: function () {

            table.resize('node-table');

        },
        success: function (layero, index, that) {

            queryNodeTable(id)
        },
        content: ` <table id="node-table" lay-filter="node-table"></table>`
    });

}

// 加载节点列表
queryNodeTable = (id) => {
    let toolWidth = window.innerWidth / 1920 * 240
    table.render({
        elem: '#node-table'
        , text: {
            none: '暂无数据'
        }
        , method: 'get'
        , url: ajaxPrefix() + "/device/electric/node/list"
        , headers: {
            SessionId: JSON.parse(localStorage.getItem('sessionId'))
        }
        , where: {
            deviceId: id,
        }
        , parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.status == 200 ? 0 : 1, //解析接口状态
                "msg": res.message, //解析提示文本
                "data": res.result
            };
        }
        , request: {
            pageName: 'pageNum' //页码的参数名称，默认：page
            ,
            limitName: 'pageSize' //每页数据量的参数名，默认：limit
        }
        // ,css: [

        //     '.layui-table-view td[data-edit]{color: #16B777;}'
        //   ].join('')
        , cols: [[ //标题栏
            { field: 'nodeName', title: '节点名称', align: "center", edit: 'editable' },
            { field: 'nodeNum', title: '节点号', align: "center", edit: 'editable' },
            {
                field: 'code', title: '节点类型', align: 'center'
                , unresize: true, align: 'center', templet: '#TPL-dropdown-demo'
            }
            , {
                title: '操作',
                align: 'center',
                width: toolWidth,
                toolbar: '#table-node-tool',
            },
        ]]
        , height: 'full'
        // ,skin: 'line' //表格风格
        , even: true
        , page: false
        , done: function (res, curr, count) {
            var options = this;
            // 获取当前行数据 - 自定义方法
            table.getRowData = function (tableId, elem) {
                var index = $(elem).closest('tr').data('index');
                return table.cache[tableId][index] || {};
            };
            // dropdown 方式的下拉选择
            layui.dropdown.render({
                elem: '.dropdown-demo',
                data: [{
                    title: '1P',
                    id: 1
                }, {
                    title: '2P',
                    id: 2
                }
                    , {
                    title: '3P',
                    id: 3
                }
                    , {
                    title: '4P',
                    id: 4
                }
                ],
                click: function (obj) {
                    var data = table.getRowData(options.id, this.elem);
                    if (obj.id == data.loopType) {
                        return
                    } else {
                        data.loopType = obj.id
                        saveNode(data);
                    }
                }
            });


            // 单元格编辑事件

            table.on('edit(node-table)', function (obj) {

                var value = obj.value // 得到修改后的值

                var data = obj.data // 得到所在行所有键值

                if (value.replace(/\s/g, '') === '') {

                    layer.tips('值不能为空', this, { tips: 1, time: 800 });

                    return obj.reedit();

                }
                saveNode(data)

            });

        }

    });
    // 行工具事件
    table.on('tool(node-table)', function (obj) {
        var that = this;
        var res = obj.data;

        var type = parseInt(obj.event);
        if (type == 1) {//配置
            openNodeConfig(res)
        } else if (type == 2) {//复位

            layer.confirm('确定进行复位操作吗', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/device/akr/ascb/command/down')
                    .setMethod('post')
                    .setData(JSON.stringify(
                        {
                            deviceId: res.deviceId,
                            nodeId: res.id,
                            deviceCode: curDeviceCode,
                            nodeNum: res.nodeNum,
                            type: 3,
                        }
                    ))
                    .enableLayer('复位成功',
                        function () { })
                    .then(data => {

                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });


        } else if (type == 3) {//删除
            layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/device/electric/node/delete')
                    .setData({ deviceId: res.deviceId, nodeId: res.id, })
                    .then(data => {
                        layer.msg('删除成功', { icon: 1, time: 1500 });
                        queryNodeTable(res.deviceId)
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });

        }
    });

}

//新增编辑节点弹窗
addNewNodes = (id, type) => {

    layer.open({
        type: 1,
        area: '40%',
        offset: ['20%'],
        resize: false,
        shadeClose: true,
        title: type == 1 ? "新增" : "编辑" + '节点',
        content: `<form class="layui-form layui-form-pane" id="node-form" lay-filter="nodeForm" action="">
                    <div class="form-item">
                        <label class="layui-form-label">节点名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="node_name" lay-affix="clear" lay-verify="required" placeholder="请输入"  class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">节点号</label>
                        <div class="layui-input-block">
                            <input type="text" name="node_num" lay-affix="clear" lay-verify="required" placeholder="请输入"  class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">节点类型</label>
                        <div class="layui-input-block">
                            <select name="loopType" lay-verify="required">
                                <option value="">请选择</option>
                                <option value=1>1P</option>
                                <option value=2>2P</option>
                                <option value=3>3P</option>
                                <option value=4>4P</option>
                             </select>
                        </div>
                    </div>
                    <div class="form-item pane-tool">
                        <div class="layui-btn layui-edit-submit" lay-submit  lay-filter="node-edit">确认</div>
                    </div>
                </form>`,
        success: function (layero, index, that) {
            form.render();

            // form.val('nodeForm', res);

            form.on('submit(node-edit)', function (data) {
                var field = data.field;

                // field.id = res.id;

                var nodeData = {
                    "deviceId": id,
                    "nodeNum": field.node_num,
                    "nodeName": field.node_name,
                    "loopType": field.loopType,
                }
                saveNode(nodeData, index)

                return false;
            });
        },
    });

}

// 保存节点信息接口
saveNode = (params, index) => {
    new AjaxChain()
        .setUrl('/device/electric/node/save')
        .setMethod('post')
        .setData(JSON.stringify(
            {
                "list": [
                    params,
                ]
            }
        ))
        .then(data => {
            if (index) {
                layer.close(index);
            }

            layer.msg('配置成功', { icon: 1, time: 2000 });
            queryNodeTable(params.deviceId)
        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();
}

// 节点阈值配置弹窗
openNodeConfig = (res) => {

    layer.open({
        type: 1,
        title: `<div style="height: 100%;display: flex;align-items: center;">阈值配置
                    <div class="table-edit layui-btn" style="margin: 0 0 0 auto;" onclick=saveNodeConfig("${res.id}","${res.deviceId}","${res.nodeNum}")>保存</div>
                </div>`,
        move: false,
        content: $('#node-config').html(),
        area: ['100%', '100%'], // 初始宽高
        success: function (layero, index) {

            new AjaxChain()
                .setUrl('/device/electric/threshold/info')
                .setData({
                    deviceId: res.deviceId,
                    nodeId: res.id,
                })
                .then(data => {
                    form.render();

                    var inputElements = document.querySelectorAll('.config-input input');


                    inputElements.forEach(function (inputElement) {
                        var resultKey = inputElement.getAttribute('data-result-key');
                        var value = data[resultKey];

                        if (inputElement.type == "checkbox") {
                            $(inputElement).prop('checked', value == 1 ? true : false)
                        } else {
                            inputElement.value = value;
                        }


                    });


                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();
        }

    });

}

// 节点阈值保存弹窗
saveNodeConfig = (nodeId, deviceId, nodeNum) => {

    form.submit('node-config-form', function (data) {

        var field = data.field; // 获取表单全部字段值
        field.nodeId = nodeId
        field.deviceId = deviceId
        field.nodeNum = nodeNum
        field.deviceCode = curDeviceCode
        $('.config-input input[type="checkbox"]').each(function () {
            var name = $(this).attr('name');
            if ($(this).prop('checked')) {
                field[name] = 1;
            } else {
                field[name] = 0;
            }
        });

        // 执行提交

        layer.confirm('确定提交吗？', function (index) {

            new AjaxChain()
                .setUrl('/device/akr/ascb/protect/down')
                .setMethod('post')
                .setData(JSON.stringify(field))
                .then(data => {
                    layer.close(index);
                    layer.msg('配置成功', { icon: 1, time: 2000 });
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();
        });

    });

    return false;


}


// 操作rfid设备
rfidAction = (id, type) => {
    new AjaxChain()
        .setUrl('/train/rfid/device/action')
        .setData(
            {
                id: id,
                action: type,
            }
        )
        .then(data => {

            layer.msg('操作成功', { icon: 1, time: 200000 });
        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();
}




// rfid配置弹窗
rfidConfig = (id) => {

    drawer = layer.open({
        title: 'rfid配置',
        type: 1,
        offset: 'r',
        anim: 'slideLeft', // 从右往左
        area: ['40%', '100%'],
        shade: 0.3,
        shadeClose: false,
        id: 'rfid-config',
        success: function (layero, index, that) {

            new AjaxChain()
                .setUrl('/train/rfid/device/config/get')
                .setData(
                    {
                        id: id
                    }
                )
                .then(data => {
                    form.val('rfid-config', data);
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();



            form.on('submit(rfidconfig)', function (data) {//监听新增修改提交

                data.field.deviceId = id;
                new AjaxChain()
                    .setUrl('/train/rfid/device/config/down')
                    .setMethod('post')
                    .setData(JSON.stringify(data.field))
                    .then(data => {
                        layer.close(drawer);
                        layer.msg('配置成功', { icon: 1, time: 2000 });
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();


                return false;
            });


        },
        content: `<form class="layui-form layui-form-pane" id="rfid-config"  lay-filter="rfid-config"  action="">
                    <div class="form-item">
                        <label class="layui-form-label">标签活跃超时时间（S）</label>
                        <div class="layui-input-block">
                            <input type="text" name="tagActiveTime" lay-affix="clear" placeholder="请输入" 
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">是否过滤其他信号差的标签</label>
                        <div class="layui-input-block">
                            <input type="text" name="rssiThreshold" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">过滤关键字</label>
                        <div class="layui-input-block">
                            <input type="text" name="filter" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">天线功率</label>
                        <div class="layui-input-block">
                            <input type="text" name="antPower" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">天线通道号</label>
                        <div class="layui-input-block">
                            <input type="text" name="antNo" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">target</label>
                        <div class="layui-input-block">
                            <select name="target" lay-filter=""">
                               <option value="">请选择</option>
                               <option value="A">A</option>
                               <option value="B">B</option>
                               <option value="A-B">A-B</option>
                               <option value="B-A">B-A</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">session</label>
                        <div class="layui-input-block">
                            <select name="session" lay-filter=""">
                               <option value="">请选择</option>
                               <option value=0>0</option>
                               <option value=1>1</option>
                               <option value=23>23</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">rfMode</label>
                        <div class="layui-input-block">
                            <select name="rfMode" lay-filter=""">
                               <option value="">请选择</option>
                               <option value=5>5</option>
                               <option value=7>7</option>
                               <option value=13>13</option>
                               <option value=103>103</option>
                            </select>
                        </div>
                    </div>
                        <div class="form-item">
                        <label class="layui-form-label">valueQ</label>
                        <div class="layui-input-block">
                            <input type="text" name="valueQ" lay-affix="clear" placeholder="0~15"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item pane-tool" >
                        <button class="layui-btn" lay-submit lay-filter="rfidconfig">确认</button>
                    </div>
                </form>`
    });

}
